package com.shujia.stream

import org.apache.spark.streaming.dstream.ReceiverInputDStream
import org.apache.spark.streaming.{Durations, StreamingContext}
import org.apache.spark.{SparkConf, SparkContext}

object Demo1WordCount {
  def main(args: Array[String]): Unit = {
    //1、创建Spark执行环境
    val conf = new SparkConf()
    conf.setAppName("wc")
    conf.setMaster("local[2]")

    val sc = new SparkContext(conf)

    /**
     * Durations.seconds(5): 指定处理批次的大小
     */
    //2、创建Spark Streaming执行环境
    val ssc = new StreamingContext(sc, Durations.seconds(5))


    /**
     * nc -lk 8888
     * nc用于模拟实时数据源的工具
     * yum install nc
     */
    //3、读取数据
    val linesDS: ReceiverInputDStream[String] = ssc.socketTextStream("master", 8888)


    //统计单词的数量
    linesDS
      .flatMap(line => line.split(","))
      .map(word => {
        println("map算子被执行")
        (word, 1)
      })
      .reduceByKey((x, y) => x + y)
      .print()


    //4、启动spark streaming程序
    ssc.start()
    ssc.awaitTermination()
    ssc.stop()
  }
}
